#!/usr/bin/env python

import optparse
import sys

import tables

from charmicat import BadCommandLineError

import ypipi

def main():
    '''
    ypipi_pi0pi0_cuts.py [opts] cut_name file.h5 [file.h5 [...]]

    Apply the cut `cut_name' (defined in ypipi.cuts) to each of the input files, 
    collating output into a single output file. 
    '''

    op = optparse.OptionParser(usage=main.__doc__)

    op.add_option("-o", "--output", dest='output', default=None,
                  help='Leave output in FILE.h5', metavar='FILE.h5')

    opts, args = op.parse_args()

    if len(args) == 0:
        msg = "Please supply a cut name and at least one PyTables file as input."
        raise BadCommandLineError(msg, -1)
        
    cut_name = args.pop(0)

    if len(args) == 0:
        msg = "Please at least one PyTables file as input."
        raise BadCommandLineError(msg, -2)

    if cut_name not in ypipi.cuts:
        msg = "Cut `{0}' not defined in ypipi.cuts"
        raise BadCommandLineError(msg, -3)
    
    if opts.output is None:
        opts.output = cut_name + '.h5'
        
    with tables.openFile(args[0]) as fpdesc:
        h5out = tables.openFile(opts.output, 'w')
        ntout = h5out.createTable(h5out.root, 'nt', fpdesc.root.nt.coldescrs,
                                  'pi0pi0 data with {0}'.format(ypipi.cuts[cut_name].pos_str))
    
    for path in args:
        h5in = tables.openFile(path)
        
        h5in.root.nt.whereAppend(ntout, ypipi.cuts[cut_name].pos_str)
    
        h5in.close()

    h5out.close()
            
        

if __name__ == "__main__":
    try:
        sys.exit(main())
    except BadCommandLineError, e:
        import os
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("See `{0} -h' for more.\n".format(os.path.basename(sys.argv[0])))
        sys.stderr.flush()
        sys.exit(e.retcode)
